package jsp;

import java.util.Calendar;

/**
 * @author Remco Haszing
 */
public class Datetime {

    /**
     * Returns the value of calendar corresponding to the character value. This
     * methos returns the value of calendar corresponding to the character
     * value.
     *
     * @param calendar The calendar to get the data from.
     * @param character The character to define the requested string.
     * @return The value of calendar corresponding to the character value.
     */
    private static String dateFormat(Calendar calendar, char character) {
        switch (character) {
            case 'Y':
                String ret = "" + calendar.get(Calendar.YEAR);
                while (ret.length() < 4) {
                    ret = 0 + ret;
                }
                return ret;
            case 'm':
                return "" + (1 + calendar.get(Calendar.MONTH));
            case 'd':
                return "" + calendar.get(Calendar.DAY_OF_MONTH);
            case 'H':
                return "" + calendar.get(Calendar.HOUR_OF_DAY);
            case 'M':
                return "" + calendar.get(Calendar.MINUTE);
            case 's':
                return "" + calendar.get(Calendar.SECOND);
        }
        return "";
    }

    /**
     * Formats a string displaying the calendar in a requested format. This
     * method returns a string representing the calendar passed as a parameter
     * in the requested format.
     *
     * @param calendar The calendar to be formatted.
     * @param format The string representing what format the return string
     * should have.
     * @return The formatted calendar string.
     */
    public static String format(Calendar calendar, String format) {
        char[] f = format.toCharArray();
        String ret = "";
        for (int i = 0; i < f.length; i++) {
            if (f[i] == '%') {
                i++;
                String q = dateFormat(calendar, f[i]);
                if (q.equals("")) {
                    i--;
                    ret += f[i];
                } else {
                    ret += q;
                }
            } else {
                ret += f[i];
            }
        }
        return ret;
    }
}
